/**
 * Copyright 2020 Makani Technologies LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Display image (png file).
 * @param {string} src Path to image file.
 */
function show_image(src) {
  var img = document.createElement('img');
  img.src = src;
  img.style = 'width:30%';
  document.getElementById('all_charts').appendChild(img);
}

/**
 * Rescores all table cells. This should be called whenever the filters are
 * modified or the 'aggregate' function is updated.
 */
function rescore() {
  if (!d3.select('#manual_selection_button').property('checked')) {
    d3.select('#active_scores').selectAll('input').each(function(d, i) {
      if (d3.select(this).attr('active_flight_mode') == 'true' &&
          d3.select(this).attr('active_system') == 'true') {
        d3.select(this).property('checked', true);
      } else {
        d3.select(this).property('checked', false);
      }
    });
  }
  document.getElementById('all_charts').innerHTML = "";

  let activeScoreIndices = [];
  let activeScoreLabels = [];
  d3.select('#active_scores').selectAll('input').each(function(d, i) {
    if (d3.select(this).property('checked')) {
      activeScoreLabels.push(d3.select(this))
      activeScoreIndices.push(i);
    }
  });

  let activeWindShearIndices = [];
  d3.select('#active_wind_shears').selectAll('input').each(function(d, i) {
    if (d3.select(this).property('checked')) {
      activeWindShearIndices.push(i);
    }
  });

  for (let i = 0; i < activeScoreIndices.length; i++) {
    h = document.createElement("H3");
    score_label = data['score_labels'][activeScoreIndices[i]];
    t = document.createTextNode(score_label);
    h.appendChild(t);
    document.getElementById('all_charts').appendChild(h);

    png_files = (data['filenames'])[score_label];

    for (let i = 0; i < activeWindShearIndices.length; i++) {
      show_image(png_files[activeWindShearIndices[i]]);
    }
  }
}

/**
 * Makes the wind shears selection checkboxes.
 * @param {string} element ID of the containing element.
 * @param {object} wind_shears List of wind shears.
 */
function makeWindShearsCheckboxes(element, wind_shears) {
  let labels =
      d3.select(element).selectAll('input').data(wind_shears).enter().append(
          'label');
  labels.append('input')
      .attr('type', 'checkbox')
      .property('checked', true)
      .on('change', rescore);
  labels.append('text').text(function(d) { return d; });
}


/**
 * Renders the score tables on a sweeps report page.
 * @param {dict} data The JSON overview data generated by a sweeps batch sim.
 * @param {string} elt ID of the HTML element that will contain the tables.
 */
function renderSelectedCharts(data, elt) {
  document.title = data['title'];
  d3.select('#report_title').text(data['title']);
  d3.select('#report_metadata').html(function() {
    parts = ['<b>Batch A</b>: ' + data['batch_a']];
    parts.push('<b>Batch B</b>: ' + data['batch_b']);
    parts.push('Summary data: ' + '<a href="./summary.txt">Text File</a>')

    return parts.join('<br>');
  });

  makeCheckboxes('#active_scores', data['metrics']);
  makeWindShearsCheckboxes('#active_wind_shears', data['wind_shears'])

  rescore();
}

/**
 * Renders the score tables on a sweeps report page.
 * @param {string} filename Path of JSON file containing overview data generated
 *     by a sweeps batch sim.
 */
function renderChartsOnPage(filename) {
  d3.json(filename, function(error, contents) {
    if (error) {
      console.log('Problem loading file ' + filename);
      console.log(error);
      d3.select('#main_section')
          .append('div')
          .style('display', 'inline-block')
          .style('text-align', 'left')
          // clang-format off
         .html(`If you are seeing this on Jenkins report page, the build has
failed. Please look at console output for errors.
<br><br>This page must be viewed from a web server because it loads
local files. If attempting to view in your browser with a file:// link, instead:
<ol>
<li>Open a terminal in the directory containing this file.
<li>Run "<tt>python -m SimpleHTTPServer 1234</tt>". You can replace
    <tt>1234</tt> with your favorite port number.
<li>Navigate to <a href="http://localhost:1234">localhost:1234</a> in your
    browser.
</ol>`);
      // clang-format on
      return;
    }
    data = contents;
    renderSelectedCharts(contents, 'body');
  });
}
